// 从外面的window引进需要的变量和方法
var generateUUID = window.parent.generateUUID;
var resourceHandler = window.parent.resourceHandler;
var bootbox = window.parent.bootbox;
var acceptTypes = window.parent.tencentVideoTypes; // 腾讯云视频上传支持的格式
var isOpenTencentVideo = window.parent.isOpenTencentVideo; // 是否开启腾讯云点播的上传
$.i18n = window.parent.$.i18n;
window.applicationPath = window.parent.globalVar.baseURL;
String.prototype.htmlEscape = window.parent.String.prototype.htmlEscape;

if(isOpenTencentVideo && fileType === 'video'){
    document.getElementById("tcFileTypeAccept").innerHTML =
        "文件限3G以内，支持格式包括wmv、wm、asf、asx、rm、rmvb、ra、ram、mpg、mpeg、mpe、vob、dat、mov、3gp、mp4、mp4v、m4v、mkv、avi、flv、f4v";
}

function submit(istx) {
    var fileValue = $("#fileValue").val();
    if (fileValue === '') {
        bootbox.warn($.i18n('messager_need_file'));
        return false;
    }
    if(istx){ // 开启了腾讯云上传
        var file = $("#fileValue")[0].files[0];
        var addedName = $("#fileName").val() || '';
        setTimeout(function () {
            window.parent.tencentUploadVideo(file, addedName);
        });
        return dialog.oncancel();
    }
    var action_url = window.applicationPath + "/api/Editor/FileUpload?t=" + fileType;
    var createStandardXHR = $.ajaxSettings.xhr;
    //$.messager.progress({
    //    title: '提示信息',
    //    msg: '文件上传中...',
    //    interval: 0  // disable auto update progress value
    //});
    //var bar = $.messager.progress('bar');  // get the progressbar object
    var bar = bootbox.dialog({
        title: $.i18n('messager_prompt'),
        message: $.i18n('messager_in_upload'),
        closeButton: false
    });
    bar.init(function () {
        var formdata = new FormData($('#formFile').get(0));
        $.ajax({
            // 重写ajax的xhr方法
            xhr: function () {
                var xhr = createStandardXHR();
                if (xhr && xhr.upload) {
                    xhr.upload.addEventListener("progress", function (event) {
                        if (event.lengthComputable) {
                            var percentComplete = Math.round(event.loaded * 100 / event.total);
                            //bar.progressbar('setValue', percentComplete);  // set new progress value
                            //bar.find('.bootbox-body').html(percentComplete + '%');
                        } else {
                            console.log('无法计算');
                        }
                    }, false);
                }
                return xhr;
            },
            type: 'POST',
            url: action_url,
            processData: false,
            contentType: false,
            data: formdata,
            success: function (data) {
                bar.modal('hide');
                if (data && data.Code === 200) {
                    if(fileType === "audio"){
                        resourceHandler.addResource({
                            type: 'nativeaudio',
                            name: $("#fileName").val(),
                            src: data.Data
                        });
                    }else{
                        editor.execCommand('insertMedia', {
                            src: data.Data,
                            uuid: generateUUID(),
                            describe: $("#fileName").val(),
                            type: fileType
                        });
                    }
                    dialog.oncancel();
                } else {
                    bootbox.fail($.i18n('messager_fail_to_upload'));
                }
            },
            error: function () {
                bar.modal('hide');
                bootbox.fail($.i18n('messager_fail_to_upload'));
            }
        });


    });
}

$('#choose').on('click', function () {
    $('#fileValue').trigger('click');
})

// 添加文件时将文件名添加到输入框
// 防止添加不符合格式的文件
$('#fileValue').on('change', function () {
    function showError(str) {
        self.val('');
        self.removeClass('input-validation-error');
        $('#fileName').val('');
        //$.messager.alert("提示信息", str, "info");
        bootbox.fail(str);
    }
    //$('#fileName').val($(this).val().replace(/^.*?([^\\]+?)(\.[^\.\\]*?)?$/g, '$1'));
    var self = $(this),
        accepts = acceptTypes,
        files = this.files,
        value = self.val();
    // 图片
    if(fileType == 'image' || fileType == 'audio'){
        accepts = self.attr('accept').split(',');
    }
    if (value) {
        for (var i = 0; i < files.length; i++) {
            if (files[i].size <= 0) {
                showError($.i18n('messager_file_size_cannot_zero'));
                return;
            }
            // 图片
            if(fileType == 'image'){
                if (files[i].size / 1024 / 1024 >= 5){
                    showError($.i18n('messager_file_size_cannot_over_5MB'));
                    return;
                }
            } else if (fileType == 'audio'){
                if (files[i].size / 1024 / 1024 >= 500){
                    showError($.i18n('messager_file_size_cannot_over_500MB'));
                    return;
                }
            } else {
                if (files[i].size / 1024 / 1024 / 1024 >= 3){
                    showError($.i18n('messager_file_size_cannot_over_3GB'));
                    return;
                }
            }
        }
        for (var i = 0; i < accepts.length; i++) {
            if (new RegExp('.*\\' + accepts[i] + '$', 'i').test(value)) {
                $('#fileName').val(value.replace(/^.*?([^\\]+?)(\.[^\.\\]*?)?$/g, '$1'));
                return;
            }
        }
        showError($.i18n('messager_unsupported_format'));
    }
});

dialog.onok = function () {
    // 图片
    if(fileType == 'image' || fileType == 'audio'){
        submit();
    }else{
        submit(isOpenTencentVideo);
    }
    return false;
}

dialog.oncancel = function () {
    $('#fileName').val('');
    $('#fileValue').val('');
    this._hide();
    this.autoReset = false;
    return false;
}
